// 路由配置文件
import { createRouter, createWebHistory } from 'vue-router';

// 懒加载路由组件
const Login = () => import('@/pages/Login.vue');
const StudentHome = () => import('@/pages/student/Home.vue');
const TeacherHome = () => import('@/pages/teacher/Home.vue');
const TeacherClassManage = () => import('@/pages/teacher/ClassManagement.vue');
const TeacherStudentManage = () => import('@/pages/teacher/StudentManagement.vue');
const TeacherHomeworkManage = () => import('@/pages/teacher/HomeworkManagement.vue');

// 创建路由实例
const router = createRouter({
  history: createWebHistory(),
  routes: [
    // 基础路由
    {
      path: '/',
      redirect: '/login'
    },
    {
      path: '/login',
      component: Login,
      meta: { title: '登录' }
    },
    
    // 学生路由
    {
      path: '/student',
      meta: { requiresAuth: true, roles: ['student'] },
      children: [
        { path: 'home', component: StudentHome, meta: { title: '学生主页' } }
      ]
    },
    
    // 教师路由
    {
      path: '/teacher',
      meta: { requiresAuth: true, roles: ['teacher'] },
      children: [
        { path: 'home', component: TeacherHome, meta: { title: '教师主页' } },
        { path: 'classes', component: TeacherClassManage, meta: { title: '班级管理' } },
        { path: 'students', component: TeacherStudentManage, meta: { title: '学生管理' } },
        { path: 'homeworks', component: TeacherHomeworkManage, meta: { title: '作业管理' } }
      ]
    },
    
    // 404页面
    {
      path: '/:pathMatch(.*)*',
      redirect: '/login'
    }
  ]
});

// 路由守卫
router.beforeEach((to, from, next) => {
  // 设置页面标题
  if (to.meta.title) {
    document.title = to.meta.title + ' - 学生作业提交系统';
  }
  
  // 检查是否需要登录
  if (to.meta.requiresAuth) {
    const token = localStorage.getItem('token');
    const userInfo = localStorage.getItem('userInfo');
    
    if (!token || !userInfo) {
      // 未登录，重定向到登录页
      return next('/login');
    }
    
    // 检查用户角色
    const user = JSON.parse(userInfo);
    if (to.meta.roles && !to.meta.roles.includes(user.role)) {
      // 角色不匹配，跳转到对应首页
      if (user.role === 'teacher') {
        return next('/teacher/home');
      } else {
        return next('/student/home');
      }
    }
  }
  
  next();
});

export default router;